<template>
  <!-- 生产计划表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="60%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="150"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div class="search-container">
          <el-row>
            <el-col :span="12">
              <el-form-item label="生产计划编号" prop="producePlanCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.producePlanCode"
                  placeholder="请输入生产计划编号"
                  clearable
                />
                <span v-else>{{ formData.producePlanCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12"
              ><el-form-item label="工厂编号" prop="plantCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.plantCode"
                  placeholder="请输入工厂编号"
                  clearable
                />
                <span v-else>{{ formData.plantCode }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="工作中心编号" prop="workCenterCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.workCenterCode"
                  placeholder="请输入工作中心编号"
                  clearable
                />
                <span v-else>{{ formData.workCenterCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划开始日期" prop="planBeginDate">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planBeginDate"
                  placeholder="请输入计划开始日期"
                  clearable
                />
                <span v-else>{{ formData.planBeginDate }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划截止日期" prop="planEndDate">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planEndDate"
                  placeholder="请输入计划截止日期"
                  clearable
                />
                <span v-else>{{ formData.planEndDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料编号" prop="materialCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.materialCode"
                  placeholder="请输入物料编号"
                  clearable
                />
                <span v-else>{{ formData.materialCode }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划数量" prop="planQuantity">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planQuantity"
                  placeholder="请输入计划数量"
                  clearable
                />
                <span v-else>{{ formData.planQuantity }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="已完成数量" prop="planFinishQuantity">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planFinishQuantity"
                  placeholder="请输入已完成数量"
                  clearable
                />
                <span v-else>{{ formData.planFinishQuantity }}</span>
              </el-form-item></el-col
            >
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="数量单位" prop="quantityUnit">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.quantityUnit"
                  placeholder="请选择数量单位"
                  clearable
                  disabled
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'MeasurementUnit'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>

                <span v-else>{{
                  useDictionary("MeasurementUnit", formData.quantityUnit)
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8" />
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column
                label="物料编号"
                props="materialCode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.materialCode'"
                    :rules="rules.sonmaterialCode"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.materialCode"
                      placeholder="请输入物料编号"
                      clearable
                    />
                    <span v-else>{{ row.materialCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="物料条码"
                props="materialBarcode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.materialBarcode'"
                    :rules="rules.sonmaterialBarcode"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.materialBarcode"
                      placeholder="请输入物料条码"
                      clearable
                    />
                    <span v-else>{{ row.materialBarcode }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <!-- <el-table-column
                label="顺序号"
                props="sequenceCode"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.sequenceCode'"
                    :rules="rules.sonsequenceCode"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.sequenceCode"
                      placeholder="请输入顺序号"
                      clearable
                    />
                    <span v-else>{{ row.sequenceCode }}</span>
                  </el-form-item>
                </template>
              </el-table-column> -->
              <!-- <el-table-column
                label="是否已下达"
                props="isRelease"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.isRelease'"
                    :rules="rules.sonisRelease"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.isRelease"
                      placeholder="请输入是否已下达"
                      clearable
                    />
                    <span v-else>{{ row.isRelease }}</span>
                  </el-form-item>
                </template>
              </el-table-column> -->

              <el-table-column
                label="需求数量"
                props="requestQuantity"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.requestQuantity'"
                    :rules="rules.sonrequestQuantity"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.requestQuantity"
                      placeholder="请输入需求数量"
                      clearable
                    />
                    <span v-else>{{ row.requestQuantity }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="已完成数量"
                props="finishQuantity"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.finishQuantity'"
                    :rules="rules.sonfinishQuantity"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.finishQuantity"
                      placeholder="请输入已完成数量"
                      clearable
                    />
                    <span v-else>{{ row.finishQuantity }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="是否已执行"
                props="isExecute"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.isExecute'"
                    :rules="rules.sonisExecute"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.isExecute"
                      clearable
                      placeholder="请选择是否已执行"
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList('YesNo')"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <span v-else>{{
                      dictionaryStore.filterDictName("YesNo", row.isExecute)
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="300"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESPRODUCEPLANADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  producePlanCode: "",
  routingAllocationId: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  workshopId: "",
  workshopCode: "",
  workshopSectionId: "",
  workshopSectionCode: "",
  workCenterId: "",
  workCenterCode: "",
  planBeginDate: "",
  planEndDate: "",
  planYear: "",
  planWeek: "",
  materialId: "",
  materialCode: "",
  planState: "",
  planQuantity: "",
  planBatch: "",
  planFinishQuantity: "",
  quantityUnit: "",
  externalCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  details: [
    {
      id: "",
      organizationId: "",
      organizationCode: "",
      plantId: "",
      plantCode: "",
      workCenterId: "",
      workCenterCode: "",
      producePlanId: "",
      producePlanCode: "",
      produceOrderId: "",
      produceOrderCode: "",
      planDate: "",
      planYear: "",
      planWeek: "",
      shiftSystemId: "",
      shiftId: "",
      materialId: "",
      materialCode: "",
      materialBarcode: "",
      sequenceCode: "",
      isRelease: "",
      isExecute: "",
      requestQuantity: "",
      finishQuantity: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      deleted: "",
      quantityUnit: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  producePlanCode: [
    { required: true, message: "请输入生产计划编号", trigger: "blur" },
  ],
  routingAllocationId: [
    { required: true, message: "请输入工艺路线分配物料主键", trigger: "blur" },
  ],
  plantId: [{ required: true, message: "请输入工厂id", trigger: "blur" }],
  plantCode: [{ required: true, message: "请输入工厂编号", trigger: "blur" }],
  workshopId: [{ required: true, message: "请输入车间id", trigger: "blur" }],
  workshopCode: [
    { required: true, message: "请输入车间编号", trigger: "blur" },
  ],
  workshopSectionId: [
    { required: true, message: "请输入工段id", trigger: "blur" },
  ],
  workshopSectionCode: [
    { required: true, message: "请输入工段编号", trigger: "blur" },
  ],
  workCenterId: [
    { required: true, message: "请输入工作中心id", trigger: "blur" },
  ],
  workCenterCode: [
    { required: true, message: "请输入工作中心编号", trigger: "blur" },
  ],
  planBeginDate: [
    { required: true, message: "请输入计划开始日期", trigger: "blur" },
  ],
  planEndDate: [
    { required: true, message: "请输入计划截止日期", trigger: "blur" },
  ],
  planYear: [{ required: true, message: "请输入计划年份", trigger: "blur" }],
  planWeek: [{ required: true, message: "请输入计划周数", trigger: "blur" }],
  materialId: [{ required: true, message: "请输入物料id", trigger: "blur" }],
  materialCode: [
    { required: true, message: "请输入物料编号", trigger: "blur" },
  ],
  planState: [{ required: true, message: "请输入生产状态", trigger: "blur" }],
  planQuantity: [
    { required: true, message: "请输入计划数量", trigger: "blur" },
  ],
  planBatch: [{ required: true, message: "请输入计划批次", trigger: "blur" }],
  planFinishQuantity: [
    { required: true, message: "请输入已完成数量", trigger: "blur" },
  ],
  quantityUnit: [
    { required: true, message: "请输入数量单位", trigger: "blur" },
  ],
  sonmaterialCode: [
    { required: true, message: "请输入物料编号", trigger: "blur" },
  ],
  sonmaterialBarcode: [
    { required: true, message: "请输入物料条码", trigger: "blur" },
  ],
  sonsequenceCode: [
    { required: true, message: "请输入顺序号", trigger: "blur" },
  ],
  sonisRelease: [
    { required: true, message: "请输入是否已下达", trigger: "blur" },
  ],
  sonisExecute: [
    { required: true, message: "请输入是否已执行", trigger: "blur" },
  ],
  sonrequestQuantity: [
    { required: true, message: "请输入需求数量", trigger: "blur" },
  ],
  sonfinishQuantity: [
    { required: true, message: "请输入已完成数量", trigger: "blur" },
  ],
  sonquantityUnit: [
    { required: true, message: "请输入数量单位", trigger: "blur" },
  ],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  workCenterId: "",
  workCenterCode: "",
  producePlanId: "",
  producePlanCode: "",
  produceOrderId: "",
  produceOrderCode: "",
  planDate: "",
  planYear: "",
  planWeek: "",
  shiftSystemId: "",
  shiftId: "",
  materialId: "",
  materialCode: "",
  materialBarcode: "",
  sequenceCode: "",
  isRelease: "",
  isExecute: "",
  requestQuantity: "",
  finishQuantity: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  quantityUnit: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [details];
  formData.id = "";
  formData.producePlanCode = "";
  formData.routingAllocationId = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.workshopId = "";
  formData.workshopCode = "";
  formData.workshopSectionId = "";
  formData.workshopSectionCode = "";
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.planBeginDate = "";
  formData.planEndDate = "";
  formData.planYear = "";
  formData.planWeek = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.planState = "";
  formData.planQuantity = "";
  formData.planBatch = "";
  formData.planFinishQuantity = "";
  formData.quantityUnit = "";
  formData.externalCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 生产计划保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/mesproduceplan/save1",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/mesproduceplan/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
